package com.health.platform.common.sys.login.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.health.platform.common.http.HttpClientUtils;
import com.health.platform.common.restful.AppResponse;
import com.health.platform.common.sys.login.entity.LoginEntity;
import com.health.platform.common.sys.login.entity.UserEntity;
import com.health.platform.common.utils.RedisUtil;
import com.health.platform.common.utils.UUIDUtils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * <p>登录Service</p>
 * <p>创建日期：2021-02-07</p>
 *
 * @author zhou-qf
 */
@Service
@Data
public class LoginService {

    @Value("${auth.loginUrl}")
    private String loginUrl;

    private String loginKey = "success";
    private String loginSuccessStr = "true";

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 登录请求
     *
     * @param loginEntity 登录请求体
     * @return 登录结果
     */
    public AppResponse login(LoginEntity loginEntity){
        HashMap param = new HashMap(2){
            {
                put("username", loginEntity.getUsername());
                put("password", loginEntity.getPassword());
            }
        };
        // 调用远程登录接口
        String result = HttpClientUtils.httpPostRequest(loginUrl, param).getContent();
        // 解析返回结果
        JSONObject jsonObject = JSON.parseObject(result);
        // 登录成功
        if(jsonObject.get(loginKey).toString().equals(loginSuccessStr)){
            UserEntity userEntity = JSONObject.parseObject(jsonObject.get("body").toString(), UserEntity.class);
            // 创建一个新的缓存KEY
            String key = UUIDUtils.getUUID();
            // 缓存
            userEntity.setLocalToken(key);
            redisUtil.set(key, userEntity);
            // 给前台返回用户登录信息
            userEntity.setToken(key);
            return AppResponse.success("登录成功", userEntity);
        } else {
            return AppResponse.bizError("登录失败");
        }
    }

}
